// <copyright file="FileUploadController.cs" company="Clever Software">
// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Clever Software</author>
// <email>info@cleversoftware.by</email>
// <date>2014-02-04</date> 
// <summary>CleverCMS source code</summary>


namespace CleverCMS.Web.Cms.Admin.Controllers
{
    using System;
    using System.Linq;
    using System.IO;
    using System.Web;
    using System.Web.Mvc;
    using System.Collections.Generic;

    using ElFinder;

    using CleverCMS.Core.Services;
    using CleverCMS.Core.Configuration;
    using CleverCMS.Core.Services.ViewModels;

    [Authorize(Roles = "Admin")]
    public class FileUploadController : Controller
    {
        private readonly FileUploadService fileUploadService;

        public FileUploadController(FileUploadService fileUploadService)
        {
            this.fileUploadService = fileUploadService;
        }

        #region Old file manager

        public ActionResult List(int? id)
        {
            ViewData["status"] = id;
            string folder = string.Format("{0}{1}/", Server.MapPath("~/"), Configuration.UploadsFolder);
            IEnumerable<FileInfo> files = this.fileUploadService.GetFiles(folder);
            files = files.OrderByDescending(x => x.CreationTime).ToList();
         
            return View(files);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadFile(FormCollection forms)
        {
            try
            {
                HttpPostedFileBase file = Request.Files["fileUpload"];

                if (null != file)
                {
                    string fullPath = this.GetFullPath(file.FileName);
                    if (!string.IsNullOrEmpty(fullPath))
                    {
                        file.SaveAs(fullPath);
                        return RedirectToAction("List", new { id = '1' });
                    }
                }
                return RedirectToAction("List", new { id = '2' });
            }
            catch (Exception)
            {
                return RedirectToAction("List", new { id = '2' });
            } 
        }

        private string GetFullPath(string fileName)
        {
            return string.Format("{0}\\{1}", Server.MapPath("~/" + Configuration.UploadsFolder), fileName);
        }

        [HttpPost]
        [Authorize]
        public ActionResult DeleteFile(string fileId)
        {
            if (!ModelState.IsValid)
            {
                var v = new { success = false, error = "Unknown error" };
                return Json(v);
            }
            try
            {
                if (null != fileId)
                {
                    string fullPath = this.GetFullPath(fileId);
                    if (System.IO.File.Exists(fullPath))
                    {
                        System.IO.File.Delete(fullPath);
                    }
                    var v = new { success = true, error = "", fileId = fileId };
                    return Json(v);
                }
                else
                {
                    var v = new { success = false, error = "Unknown error" };
                    return Json(v);
                }
            }
            catch (Exception exc)
            {
                var v = new { success = false, error = exc.Message };
                return Json(v);
            }
            //return RedirectToAction("List");
        }

        #endregion

        #region elFinder

        public ActionResult Index(string folder, string subFolder)
        {
            var driver = new FileSystemDriver();
            var root = new Root(new DirectoryInfo(Server.MapPath("~/Uploads/" + folder)), Url.Content("~/Uploads/") + folder)
            {
                IsReadOnly = false,
                Alias = "Files", 
                MaxUploadSizeInKb = 500, 
                LockedFolders = new List<string>(new string[] { "Folder1" })
            };

            if (!string.IsNullOrEmpty(subFolder))
            {
                root.StartPath = new DirectoryInfo(Url.Content("~/Uploads/" + folder + "/" + subFolder));
            }

            driver.AddRoot(root);
            var connector = new Connector(driver);
            return connector.Process(HttpContext.Request);
        }

        public ActionResult SelectFile(string target)
        {
            var driver = new FileSystemDriver();
            driver.AddRoot(new Root(new DirectoryInfo(Server.MapPath("~/Uploads/")), Url.Content("~/Uploads/")) { IsReadOnly = false });
            var connector = new Connector(driver);
            return Json(connector.GetFileByHash(target).FullName);
        }

        public ActionResult Files(string subFolder)
        {
            var model = new FileViewModel { Folder = "MyFolder", SubFolder = "MyFiles" };
            return View("FilesForm", model);
        }

        #endregion
    }
}